#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name: PyGulesider.py
# Info: This program lets you search the phone book on www.gulesider.no
# using names, phone numbers and/or locations

# Copyright 2008 Morten André Steinsland (morten.a.steinsland@gmail.com)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# TODO LIST:
#    Show more than 10 hits if there are more.
#    Show more than one phone number per hit if there are more.
#    Make it into a nice module
#    Add more error catching

import urllib
from os import system as konsoll #Only imported to clear screen

def getHtml(searchstring):
    "This returns the html from Gulesider.no"
    
    SearchWords = searchstring.split()
    Parameter = "/search.c?q="
    #ParameterEnd = "&x=0&y=0"
    
    for words in SearchWords:
        Parameter = Parameter + words + "+"
        Gulesider = urllib.urlopen("http://www.gulesider.no/tk" + Parameter[:-1])
        HTML = Gulesider.read()
    
    return HTML

def getHits(htmlfeed):
    "This function returns the number of hits as integer"
    
    if htmlfeed.find('S&oslash;ket ditt gav ingen treff i Telefonkatalogen') > -1:
        HowManyHits = 0
        return HowManyHits
    
    elif htmlfeed.find('S&oslash;ket ga ikke treff i Telefonkatalogen&trade;,') > -1:
        HowManyHits = 0
        return HowManyHits
    
    else:
        prestring = "<span>S&oslash;ket ga "
        poststring = " treff</span>"
        
        HowManyHits = htmlfeed[
                               htmlfeed.find(prestring) + len(prestring):
                               htmlfeed.find(poststring)]
        
        HowManyHits = int(HowManyHits.replace(',' , ''))
        
        return HowManyHits

def getPages(htmlfeed):
    "Return the number of pages found on Gulesider.no"
    prestring = '<li class="pageCount">'
    #poststring = ''

    if htmlfeed.find(prestring) > -1:
        
        NumberOfPages = htmlfeed[
                                 htmlfeed.index(prestring) + len(prestring):
                                 htmlfeed.index(prestring) + len(prestring)+20]
        
        NumberOfPages = NumberOfPages.split('<')[0]
        NumberOfPages = NumberOfPages.split('/')[1]
               
        return int(NumberOfPages)
    
    else:
        
        return 1

def getPostsHtml(htmlfeed):
    "This should make the search results a little nicer to work with. Returns a list"
    prestring = '<!-- RESULT ITEM START -->'
    poststring = '<!-- RESULT ITEM END -->'

    postspart = htmlfeed[
                         htmlfeed.find(prestring):
                         htmlfeed.rfind(poststring) + len(poststring)]
    
    posts = postspart.splitlines()
    
    #Create a more manageable list of data
    data = list()
    for lines in posts:
        line = lines.strip()
        if line != '':
            data.insert(len(data), line)
            
    return data
        
def getPost(htmlfeedlist, postnumber):
    "This extracts individual posts as a string from the list of html made by getPostsHtml()"
    string = ''.join(htmlfeedlist)
    strings = string.split('<!-- RESULT ITEM END -->')
    
    return strings[postnumber]

def getName(htmlstring):
    "Returns the name from a string served by getPost"
    prestring = '<p class="oppfnavn">'
    poststring = '</p>'
    
    name = htmlstring[htmlstring.find(prestring) + len(prestring):]
    name = name[:name.find(poststring)]
    
    return name

def getPhoneNumber(htmlstring):
    "Returns the phone number as integer from a string served by getPost"
    prestring = '<div class="tlf mainNr">'
    poststring = '</div>'
    mobileprestring = 'Send SMS til nummer">' #If the string contains this it's a cellphone number
    mobilepoststring = '</a>'
        
    if htmlstring.find(mobileprestring) > -1:
        #This contains a link to send sms
        phone = htmlstring[htmlstring.find(mobileprestring) + len(mobileprestring):]
        phone = phone[:phone.find(mobilepoststring)]
        phone = phone.replace(' ','')
        
        return phone
        
    else:
        #This does not contain sms link
        phone = htmlstring[htmlstring.find(prestring) + len(prestring):]
        phone = phone[:phone.find(poststring)]
        phone = phone.replace(' ','')
                
        return phone
           
def getAddress(htmlstring):
    "Returns the address from a string served by getPost"
    prestring = '<div class="adr"><div class="lead" style="padding-left: 0px;">'
    poststring = '</div>'
    
    address = htmlstring[htmlstring.find(prestring) + len(prestring):]
    address = address[:address.find(poststring)]
    
    return address

def echoPost(postnumber):
    "This function prints the name, address and phone"
    print '---------------------------------------'
    print 'Name: ' + getName(getPost(getPostsHtml(html) , postnumber))
    print 'Address: ' + getAddress(getPost(getPostsHtml(html) , postnumber))
    print 'Phone: ' + getPhoneNumber(getPost(getPostsHtml(html) , postnumber))
    
    return

SearchFor = raw_input('Search for: ') #Get the search string from the user
konsoll("cls") #Clear console screen. Comment out if it causes problems
print "Searching for: " + str(SearchFor) #Echo the search string
html = getHtml(SearchFor) #Get the html from gulesider.no
print "Hits: " + str(getHits(html)) #Echo the number of hits

#### Use any of these to get more info for debugging
#print getPostsHtml(html)
#print getPost(getPostsHtml(html) , number)

# Print the results if there are any
if getHits(html) == 0:
    print "Nothing Found!"

else: #Shows 10 or less posts
    showpost = 0
    while showpost < getHits(html) and showpost < 10:
        echoPost(showpost)
        showpost = showpost + 1